//
//  ShopSelectViewController.swift
//  AutoPrint
//
//  Created by David on 2016/12/4.
//  Copyright © 2016年 fatcat. All rights reserved.
//

import UIKit
import CoreLocation
class ShopSelectViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate {

    var step0VC: UIViewController?
    
    var tableView: UITableView!
    
    var shopList: NSArray?
    
    var currentLocation: String?
    
    var filesInfos: NSArray?
    
    var locateMan: CLLocationManager!
    var locating = false
    var locateBtn: UIButton!
    var locatingSpinner: UIActivityIndicatorView!
    var locationLabel: UILabel!
    
    convenience init(files: NSArray){
        self.init()
        filesInfos = files
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "选择商家"
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: nil, action: nil)
        let locationDefault = NSUserDefaults.standardUserDefaults().objectForKey("location") as? String
        if locationDefault != nil {
            currentLocation = locationDefault
        }
        
        tableView = UITableView(frame: view.frame, style: .Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        
        locationLabel = UILabel(frame: CGRect(x: 52, y: 8, width: view.bounds.width - 100, height: 28))
        locationLabel.text = "正在定位"
        if currentLocation != nil{
            locationLabel.text = currentLocation
        }
        
        locateBtn = UIButton(type: .System)
        locateBtn.frame = CGRect(x: view.bounds.width - 40, y: 8, width: 32, height: 28)
        locateBtn.setTitle("定位", forState: .Normal)
        locateBtn.addTarget(self, action: #selector(ShopSelectViewController.getLocation), forControlEvents: .TouchUpInside)
        
        locatingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
        locatingSpinner.center = locateBtn.center
        
        getLocation()
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if shopList != nil{
            return shopList!.count + 1
        }
        return 2
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 44
        }else{
            return 88
        }
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "shop")
        
        if indexPath.row == 0{
            
            let locaIcon = UIImageView(frame: CGRect(x: 16, y: 8, width: 28, height: 28))
            locaIcon.image = UIImage(named: "address")
            cell.addSubview(locaIcon)
            
            
            
            cell.addSubview(locationLabel)
            cell.addSubview(locateBtn)
            cell.addSubview(locatingSpinner)
            
//            let selectBtn = UIButton(type: .System)
//            selectBtn.frame = CGRect(x: view.bounds.width - 80, y: 8, width: 72, height: 28)
//            selectBtn.setTitle("手动选择", forState: .Normal)
//            cell.addSubview(selectBtn)
            
        }else{
            var empty = true
            if shopList != nil{
                if shopList!.count > 0{
                    empty = false
                    
                    
                    let shopInfo = shopList?.objectAtIndex(indexPath.row - 1) as! NSArray
                    let shopItem = shopInfo.objectAtIndex(0) as! NSDictionary
                    
                    let shopName = shopItem.objectForKey("nickname") as? String
                    let shopImage = shopItem.objectForKey("logo") as? String
                    let shopDistance = shopItem.objectForKey("distance") as? Int
                    
                    var shopRate = shopItem.objectForKey("star") as? Double
                    if shopRate == nil{
                        let shopRateStr = shopItem.objectForKey("star") as? String
                        if shopRateStr != nil{
                            shopRate = Double(shopRateStr!)
                        }
                    }
                    
                    var shopSale = shopItem.objectForKey("sales") as? Int
                    if shopSale == nil{
                        let shopSaleStr = shopItem.objectForKey("sales") as? String
                        if shopSaleStr != nil {
                            shopSale = Int(shopSaleStr!)
                        }
                    }
                    
//                    let minPrice = shopItem.objectForKey("min_price") as? Double
//                    let maxPrice = shopItem.objectForKey("max_price") as? Double
                    let prices = shopInfo.objectAtIndex(1) as! NSDictionary
                    //print(prices)
                    
                    var minPrice = Double(MAXFLOAT)
                    var maxPrice = 0.0
                    for item in prices.allValues{
                        let priceInfo = item as! NSDictionary
                        let priceStr = priceInfo.objectForKey("price") as? String
                        if priceStr != nil{
                            let price = Double(priceStr!)
                            if price != nil {
                                if price! < minPrice{
                                    minPrice = price!
                                }
                                if price! > maxPrice{
                                    maxPrice = price!
                                }
                            }
                        }
                        
                    }
                    
                    let icon = UIImageView(frame: CGRect(x: 16, y: 8, width: 72, height: 72))
                    icon.backgroundColor = UIColor.grayColor()
                    cell.addSubview(icon)
                    
                    let nameLabel = UILabel(frame: CGRect(x: 96, y: 8, width: view.bounds.width - 96 - 72, height: 20))
                    cell.addSubview(nameLabel)
                    
                    let distanceLabel = UILabel(frame: CGRect(x: view.bounds.width - 64, y: 8, width: 56, height: 20))
                    distanceLabel.textAlignment = .Right
                    distanceLabel.textColor = UIColor.grayColor()
                    distanceLabel.font = UIFont.systemFontOfSize(12)
                    cell.addSubview(distanceLabel)
                    
                    let rate = UIView(frame: CGRect(x: 96, y: 36, width: view.bounds.width - 104, height: 12))
                    cell.addSubview(rate)
                    
                    let rateLabel = UILabel(frame: CGRect(x: 70, y: 0, width: rate.bounds.width - 78, height: 12))
                    rateLabel.font = UIFont.systemFontOfSize(12)
                    rateLabel.textColor = UIColor.grayColor()
                    rate.addSubview(rateLabel)
                    
                    
                    if shopRate != nil{
                        let star = shopRate!
                        for i in 0..<5 {
                            let starIcon = UIImageView(frame: CGRect(x: CGFloat(i)*14, y: 0, width: 12, height: 12))
                            if star - Double(i) > 1{
                                
                                starIcon.image = UIImage(named: "star")
                            }else if star - Double(i) >= 0.5{
                                starIcon.image = UIImage(named: "star_half")
                            }else{
                                starIcon.image = UIImage(named: "star_gray")
                            }
                            rate.addSubview(starIcon)
                        }
                        
                        rateLabel.text = "\(String(format: "%0.1lf", star))  "
                        
                        
                    }
                    
                    if shopSale != nil{
                        if shopRate != nil{
                            rateLabel.text! += "月销"
                        }else{
                            rateLabel.center.x -= 70
                            rateLabel.text = "月销"
                            
                        }
                        
                        if shopSale! >= 999 {
                            rateLabel.text! += "999+"
                        }else{
                            rateLabel.text! += "\(shopSale!)"
                        }
                    }
                    
                    
                    
                    let subLabel = UILabel(frame: CGRect(x: 96, y: 56, width: view.bounds.width - 104, height: 24))
                    subLabel.textColor = UIColor.orangeColor()
                    cell.addSubview(subLabel)
                    
                    
                    
                    if String(format: "%.2lf", minPrice) == String(format: "%.2lf", maxPrice) {
                        subLabel.text = "￥\(String(format: "%0.2lf", minPrice))"
                    }else{
                        subLabel.text = "￥\(String(format: "%0.2lf", minPrice)) ~ \(String(format: "%0.2lf", maxPrice))"
                    }
                    
                    if shopImage != nil{
                        let imageURL = NSURL(string: shopImage!)
                        if imageURL != nil{
                            NSURLSession.sharedSession().dataTaskWithURL(imageURL!, completionHandler: { (data:NSData?, resp:NSURLResponse?, err:NSError?) in
                                if err == nil{
                                    if data != nil{
                                        let image = UIImage(data: data!)
                                        icon.image = image
                                    }
                                }
                            })
                        }
                    }
                    
                    nameLabel.text = shopName
                    
                    if shopDistance != nil{
                        distanceLabel.text = "\(shopDistance!)m"
                    }
                    
                    
                    
                    
                }
            }
            
            if empty {
                let emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
                emptyLabel.textAlignment = .Center
                emptyLabel.text = "暂无可选商家"
                cell.addSubview(emptyLabel)

                
            }
        }
        
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if indexPath.row > 0{
            if shopList != nil {
                if shopList!.count > 0{
                    let thisShopInfo = shopList?.objectAtIndex(indexPath.row - 1) as! NSArray
                    let ordVC = OrderSumupViewController(files: filesInfos!, shopInfo: thisShopInfo)
                    ordVC.step0VC = self.step0VC
                    navigationController?.pushViewController(ordVC, animated: true)
                }
            }
            
        }
    }
    
    func getLocation(){
        if !locating {
            if CLLocationManager.locationServicesEnabled(){
                locateMan = CLLocationManager()
                locateMan.delegate = self
                
                locateMan.requestWhenInUseAuthorization()
                locateMan.startUpdatingLocation()
                locateBtn.alpha = 0
                locatingSpinner.startAnimating()
                locating = true
            }else{
                UIAlertView(title: "定位不可用", message: "请前往设置->隐私->定位服务，打开定位服务，并允许\(Fatcat.PRODUCT_NAME)使用定位服务。", delegate: nil, cancelButtonTitle: "OK").show()
            }
        }
        
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(locations.last!) { (clps:[CLPlacemark]?, err:NSError?) in
            manager.stopUpdatingLocation()
            if self.locating{
                if err == nil{
                    
                    if locations.count > 0{
                        self.locating = false
                        
                        let longitude = locations.last!.coordinate.longitude
                        let latitude = locations.last!.coordinate.latitude
                        
                        let position = "\(longitude),\(latitude)"
                        print(position)
                        // TODO: 请求服务器，处理返回的列表
                        
                        var keywords = ""
                        
                        let amapURL = NSURL(string: "http://restapi.amap.com/v3/geocode/regeo?key=\(Fatcat.AMAP_API_KEY)&location=\(position)&poitype=&radius=1000&extensions=all&batch=false&roadlevel=0")
                        let amapResq = NSURLRequest(URL: amapURL!)
                        NSURLSession.sharedSession().dataTaskWithRequest(amapResq, completionHandler: { (data:NSData?, resp:NSURLResponse?, err:NSError?) in
                            if err == nil {
                                if data != nil{
//                                    print(NSString(data: data!, encoding: NSUTF8StringEncoding))
                                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                                    if jsonObj != nil {
                                        let jsonDic = jsonObj as? NSDictionary
                                        if jsonDic != nil{
                                            let status = jsonDic?.objectForKey("status") as! String
                                            if status == "1" {
                                                let region = jsonDic?.objectForKey("regeocode") as! NSDictionary
                                                let pois = region.objectForKey("pois") as! NSArray
                                                let firstPos = pois.objectAtIndex(0) as! NSDictionary
                                                keywords = firstPos.objectForKey("name") as! String
                                                dispatch_async(dispatch_get_main_queue(), { 
                                                    self.currentLocation = keywords
                                                    self.locationLabel.text = self.currentLocation
                                                })
                                                
                                                
//                                                self.shopList = NSArray(array: fakeData)
                                            }
                                        }
                                    }
                                }
                            }
                            
                            /*
                            // 本地假数据
                            let filePath = NSBundle.mainBundle().pathForResource("temp", ofType: ".json")
                            if filePath != nil{
                                let jsonStr = NSData(contentsOfFile: filePath!)
                                if jsonStr != nil{
                                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(jsonStr!, options: .AllowFragments)
                                    if jsonObj != nil{
                                        let jsonDic = jsonObj as? NSDictionary
//                                        print(jsonDic)
                                        if jsonDic != nil{
                                            let returnData = jsonDic?.objectForKey("data") as? NSDictionary
                                            if returnData != nil{
//                                                print(returnData)
                                                
                                                self.shopList = NSArray(array: returnData!.allValues)
                                                
                                                dispatch_async(dispatch_get_main_queue(), {
                                                    self.locateBtn.alpha = 1
                                                    self.locatingSpinner.stopAnimating()
                                                    
                                                    self.tableView.reloadData()
                                                })
                                                
                                                
                                            }
                                            
                                        }
                                        
                                    }
                                }
                                
                            }
                            */
                            
                            let businessResq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
                            businessResq.HTTPMethod = "POST"
                            //
                            let kvString = "act=businessList&lotude=\(String(format: "%.8lf", longitude))&latude=\(String(format: "%.8lf", latitude))&keywords="
                            print(kvString)
                            businessResq.HTTPBody = kvString.dataUsingEncoding(NSUTF8StringEncoding)
                            
                            NSURLSession.sharedSession().dataTaskWithRequest(businessResq, completionHandler: { (data:NSData?, resq:NSURLResponse?, err:NSError?) in
                                if err == nil{
                                    if data != nil{
                                        print(String(data: data!, encoding: NSUTF8StringEncoding))
                                        let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                                        if jsonObj != nil{
                                            let jsonDic = jsonObj as? NSDictionary
                                            if jsonDic != nil {
                                                dispatch_async(dispatch_get_main_queue(), { 
                                                    self.locateBtn.alpha = 1
                                                    self.locatingSpinner.stopAnimating()
                                                })
                                                let returnData = jsonDic?.objectForKey("data") as? NSDictionary
                                                if returnData != nil{
                                                    print(returnData)
                                                    self.shopList = NSArray(array: returnData!.allValues)
                                                    
                                                    dispatch_async(dispatch_get_main_queue(), {
                                                        self.locateBtn.alpha = 1
                                                        self.locatingSpinner.stopAnimating()
                                                        
                                                        self.tableView.reloadData()
                                                    })
                                                }
                                            }
                                        }
                                    }
                                }
                            }).resume()
                            
                        }).resume()
                        
                        
                        
//                        let fakeData = NSMutableArray()
//                        let fakeShop = NSMutableDictionary()
//                        fakeShop.setValue("商家名称", forKey: "shop_name")
//                        fakeShop.setValue("http://", forKey: "image")
//                        fakeShop.setValue(233, forKey: "distance")
//                        fakeShop.setValue(4.5, forKey: "rate")
//                        fakeShop.setValue(233, forKey: "sale")
//                        
//                        let price = NSMutableArray()
//                        price.addObject(["single_blackwhite":0.1])
//                        price.addObject(["single_color":1.0])
//                        fakeShop.setValue(price, forKey: "price")
////                        fakeShop.setValue(0.1, forKey: "min_price")
////                        fakeShop.setValue(1.0, forKey: "max_price")
//                        fakeShop.setValue("XX省XX市XX区XX镇XXXXXXXX附近", forKey: "address")
//                        fakeShop.setValue("12345678910", forKey: "phone")
//                        fakeShop.setValue("商家描述，可能有好多行，需要动态调整高度，具体是先在init的时候，计算好文字的高度，然后利用代理设置第0节第3行（就是现在你在看的这一行）的高度，然后还要设置这个Label的高度，要一致，而且设置他多行显示，否则默认是单行的。", forKey: "description")
//                        
//                        fakeData.addObject(fakeShop)
//                        
//
//                        
//                        self.shopList = NSArray(array: fakeData)
                        
                        //TODO: 写死计时演示
//                        if #available(iOS 10.0, *) {
//                            NSTimer.scheduledTimerWithTimeInterval(3, repeats: false, block: { (timer) in
//                                dispatch_async(dispatch_get_main_queue(), {
//                                    
//                                    self.locateBtn.alpha = 1
//                                    self.locatingSpinner.stopAnimating()
//                                    //self.locationLabel.text = self.currentLocation
//                                    self.tableView.reloadData()
//                                })
//                            })
//                        } else {
//                            dispatch_async(dispatch_get_main_queue(), {
//                                
//                                self.locateBtn.alpha = 1
//                                self.locatingSpinner.stopAnimating()
//                                
//                                self.tableView.reloadData()
//                            })
//                        }
                        
                    }
                    
                    
                    
                    
                    
                }else{
                    
                }
            }
            
            
            
            
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
